import Taro, {Component, Config} from "@tarojs/taro";
import {toJS} from "mobx";
import {ScrollView, View, Text, Image} from "@tarojs/components";
import {IStoreProps} from '../../store/Stores'
import {getRuntime,pageSize} from '../../utils/common'
import './index.less'

import {inject, observer} from "@tarojs/mobx";

interface IHomeProps extends IStoreProps {
}

@inject("stores")
@observer
class Index extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  state = {
    items: [], // 律师列表
    totalCount: 0,
    areasOfExpertise: [], // 律师标签
    allProvince: [],
    allCity: [],
    allDistrict: [],
    provinceId: -1,
    cityId: -1,
    districtId: -1,
    labelId: null,
    pageIndex: 1,
    pageSize,
  }

  componentWillMount() {
    Taro.setNavigationBarTitle({ title:'律政中心' })
    this.getAllProvince()
    this.getAllCity()
    this.getAllDistract()
    this.getAreasOfExpertise()
    this.getAllLawyerInfo()
  }

  getAllProvince() {
    let { AreaStore } = this.props.stores
    AreaStore.getAllProvinceFromLocal({
      callBack: res => {
        this.setState({
          allProvince: res
        })
      }
    })
  }

  getAllCity(index:number=-1) {
    let { AreaStore } = this.props.stores
    AreaStore.getAllCityFromLocal({
      index,
      callBack: res => {
        this.setState({
          allCity: res
        })
      }
    })
  }

  getAllDistract(indexProvince:number=-1,indexCity:number=-1) {
    let { AreaStore } = this.props.stores
    AreaStore.getAllDistractFromLocal({
      indexProvince,
      indexCity,
      callBack: res => {
        this.setState({
          allDistrict: res
        })
      }
    })
  }

  // 获取所有标签
  getAreasOfExpertise(){
    const {stores: {LegalStore}} = this.props
    LegalStore.getAreasOfExpertise({
      callback: (res) => {
        this.setState({
          areasOfExpertise: toJS(res.items)
        })
      }
    })
  }

  // 获取所有律师列表
  getAllLawyerInfo(){
    let { allProvince,allCity,allDistrict,provinceId,cityId,districtId,pageIndex,pageSize,labelId } = this.state
    const {stores: {LegalStore}} = this.props
    console.log('cityID:'+cityId)
    LegalStore.getAllLawyerInfo({
      formProvinceId: provinceId !== -1 ? allProvince[provinceId]['value'] : null,
      formCityId: cityId !== -1 ? allCity[cityId]['value'] : null,
      formDistrictId: districtId !== -1 ? allDistrict[districtId]['value'] : null,
      formAreasOfExpertiseId: labelId,
      pageIndex,
      pageSize,
      callback: (res) => {
        let resArr = toJS(res)
        // 转换擅长领域
          resArr.items.map(item => {
          return item.areaName = this._getAreaNameById(item.areasOfExpertise)
        })
        if (pageIndex === 1) {
          this.setState({totalCount: toJS(res.totalCount), items: toJS(res.items)
          })
        }else {
          const { items } = this.state;
          items.push(...res.items || []);
          this.setState({totalCount: res.totalCount, items
          })
        }
      }
    })
  }
  onReachBottom(): void {
    let {totalCount, pageSize, pageIndex} = this.state
    const {loading} = this.props.stores.homeStore;
    if (totalCount > pageIndex * pageSize && !loading) {
      this.setState({
        pageIndex: pageIndex + 1
      }, () => {
        this.getAllLawyerInfo()
      })
    }
  }
  // 根据标签ID获取标签值
  _getAreaNameById(ids: string): any{
    let value = []
    let AreasOfExpertise = this.state.areasOfExpertise
    // let idArr = ids.split(',').filter(item => parseInt(item))
    AreasOfExpertise.map(item => {
      if(ids.includes(item['id'])){
        value.push({
          id: item['id'],
          title: item['areaName'],
        })
      }
    })
    // console.log(value)
    return value
  }

  handelRouter(url: string = '/pages/index/index'): void {
    getRuntime().navigateTo(url)
  }

  /**
   * @param type
   * @param column  [0:省,1:市,2:区]
   * @param value 对应省市区的索引值
   */
  changeOption(type: string, column: number, value?: number) {
    let { allProvince,allCity,allDistrict } = this.state
    console.log(value)
    if(column===0){
      this.getAllCity(value)
      this.getAllDistract(value,0)
      let cityId = value === -1 ? -1 : 0
      let districtId = value === -1 ? -1 : 0
      this.setState({
        [type]: value,
        cityId,
        districtId
      }, () => {
        this.getAllLawyerInfo()
      })
    }
    else if(column===1){
      this.getAllDistract(this.state.provinceId,value)
      let districtId = value ===-1 ? -1 : 0
      this.setState({
        [type]:value,
        districtId,
      }, () => {
        this.getAllLawyerInfo()
      })
    }
    else {
      this.setState({
        [type]:value,
      }, () => {
        this.getAllLawyerInfo()
      })
    }
  }

  changeLabel(id:number) {
    this.setState({
      labelId: id
    },() => {
      this.getAllLawyerInfo()
    })
  }
  render() {
    let { items, allProvince, allCity, allDistrict, areasOfExpertise, provinceId, cityId, districtId, labelId } = this.state

    let item_tpl = items.map(item => {
      return (
        <View className='item' key={item.id} onClick={this.handelRouter.bind(this, `/pages/legal/detail?id=${item.id}`)}>
          <Image src={item.logoImg} className='lawyer-header'/>
          <View className='lawyer-info'>
            <View className='line1'>
              <Text className='lawyer-title'>{item.name} {item.jobPosition}</Text>
              <Text className='lawyer-help'>已帮助{item.helpAmount}人</Text>
            </View>
            <View className='line2'>
              <Text className='address'>{item.officeAddress}</Text>
            </View>
            <View className='line3'>
              {
                item.areaName.map(label => {
                  return(
                    <Text className='label' key={label.id}>{label.title}</Text>
                  )
                })
              }
            </View>
          </View>
        </View>
      )
    })

    return (
      <View>
        <View className='lawyer-wrap'>
          <View className='select-option pb0'>
            <View className='option-item' >
              <View className={provinceId === -1 ? 'option  option-active' : 'option'}
                    onClick={this.changeOption.bind(this,'provinceId',0,-1)}
              >全部</View>
              <ScrollView
                className='scrollview'
                scrollX
                scrollWithAnimation
              >
                {
                  allProvince.map((item, index) => {
                    return(
                      <View className={provinceId === index ? 'option  option-active' : 'option'} key={item.id}
                            onClick={this.changeOption.bind(this,'provinceId',0,index)}
                      >{item.label}</View>
                    )
                  })
                }
              </ScrollView>
            </View>

            <View className='option-item'
                  style={allCity.length<=0 ? {'display': 'none' } : ''}
            >
              <View className={cityId===-1 ? 'option  option-active' : 'option'}
                    onClick={this.changeOption.bind(this,'cityId',1,-1)}
              >全部</View>
              <ScrollView
                className='scrollview'
                scrollX
                scrollWithAnimation
                onScroll={this.onScroll}
              >
                {
                  allCity.map((item,index) => {
                    return(
                      <View className={cityId === index ? 'option  option-active' : 'option'} key={item.id}
                            onClick={this.changeOption.bind(this, 'cityId',1,index)}>{item.label}</View>
                    )
                  })
                }
              </ScrollView>
            </View>

            <View className='option-item' style={allDistrict.length<=0 ? {'display':'none'} : ''}>
              <View className={districtId===-1 ? 'option  option-active' : 'option'}
                    onClick={this.changeOption.bind(this,'districtId',2,-1)}
              >全部</View>
              <ScrollView
                className='scrollview'
                scrollX
                scrollWithAnimation
              >
                {
                  allDistrict.map((item,index) => {
                    return(
                      <View className={districtId === index ? 'option  option-active' : 'option'} key={item.value}
                            onClick={this.changeOption.bind(this, 'districtId',2,index)}
                      >{item.label}</View>
                    )
                  })
                }
              </ScrollView>
            </View>
            {
              areasOfExpertise.length>0&&
            <View className='option-item'>
              <View className={!labelId ? 'option  option-active' : 'option'} onClick={this.changeLabel.bind(this, null)}>全部</View>
              <ScrollView
                className='scrollview'
                scrollX
                scrollWithAnimation

              >
                {
                  areasOfExpertise.map(item => {
                    return(
                      <View className={labelId === item.id ? 'option  option-active' : 'option'} key={item.id}
                            onClick={this.changeLabel.bind(this, item.id)}
                      >{item.areaName}</View>
                    )
                  })
                }
              </ScrollView>
            </View>
            }
          </View>

          <View className='interval' />

          {items.length > 0
            ? <View className='list-2 pb0'>{item_tpl}</View>
            : <View className='page-footer'>没有相关律师信息~</View>
          }
        </View>
      </View>
    )
  }
}

export default Index
